<template>
  <div class="detail-wrap">
    <span class="tips">
      <img src="@/assets/images/Sharing@2x.png" alt width="15" /> 分享
    </span>
    <!-- <img :src="details.img_url" alt="" width="100%"> -->
    <van-image :src="details.img_url" width="100%" height="30vh"></van-image>
    <div class="bg-white p10">
      <p>{{details.title}}</p>
      <div class="price">
        <b>&yen;{{(details.price||0).toFixed(2)}}</b>
        <em>剩余{{details.unit_num}}{{details.unit}}</em>
      </div>
    </div>
    <div class="bg-white">
      <van-divider>图文详情</van-divider>
      <div class="p10 detail-cont" v-html="details.detail"></div>
      <!-- <img src="https://img.yzcdn.cn/vant/cat.jpeg" alt="" width="100%"> -->
    </div>
    <div class="btn-fix">
      <van-button type="primary" size="large" @click="show = true">立即购买</van-button>
    </div>
    <van-popup v-model="show" closeable position="bottom" class="wrapper">
      <div class="pro-wrap">
        <img :src="details.img_url" alt />
        <div>
          <b>{{details.short_title}}</b>
          <b>&yen;{{(details.price||0).toFixed(2)}}</b>
          <p>
            数量：
            <van-stepper v-model="num" integer />
          </p>
        </div>
      </div>
      <div
        class="addressBox"
      >地址:{{defaultAddress.id ? defaultAddress.street1 + defaultAddress.street2 : '暂无默认地址'}}</div>
      <van-button type="primary" size="large" @click="addOrder">确认购买</van-button>
    </van-popup>
  </div>
</template>
<script>
import { productsView, ordersAdd, ordersPay } from "@/api/products.js";
import { addressIndex } from "@/api/address.js";
import { getWxConfig } from "@/api/mine.js";
import { Dialog, Toast } from "vant";
import { mapGetters } from "vuex";

var wx = require("weixin-js-sdk");
export default {
  data() {
    return {
      show: false,
      num: 1,
      id: "",
      details: {},
      defaultAddress: {}
    };
  },
  computed: {
    ...mapGetters(["userId", "addressId"])
  },
  methods: {
    addOrder() {
      let that = this;
      //确认购买
      let num = this.num;
      if (num > this.details.unit_num) {
        Toast("库存不够了~");
        return;
      }
      if (this.defaultAddress.id) {
        Dialog.confirm({
          title: "确认地址",
          message: "将送往" + that.defaultAddress.street2 + ",是否更换地址?"
        })
          .then(() => {
            /**未选择收货地址 */
            Toast({
              message: "前往选择收货地址",
              overlay: true,
              loadingType: "spinner",
              onClose: () => {
                let params = {
                  product_id: that.id,
                  user_id: that.userId,
                  num: num
                };
                that.$router.push({
                  name: "addressList",
                  query: { params: params }
                });
              }
            });
            return;
          })
          .catch(() => {
            // on cancel
            Toast({
              message: "正在生成订单!",
              overlay: true,
              loadingType: "spinner",
              onClose: () => {
                let params = {
                  product_id: that.id,
                  user_id: that.userId,
                  num: num,
                  address_id: that.defaultAddress.area_id
                };
                ordersAdd(params).then(res => {
                  ordersPay(res).then(payData => {
                    wx.ready(function() {
                      wx.chooseWXPay({
                        appId: payData.appId,
                        timestamp: payData.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                        nonceStr: payData.nonceStr, // 支付签名随机串，不长于 32 位
                        package: payData.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                        signType: payData.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                        paySign: payData.paySign, // 支付签名
                        success: function() {
                          // 支付成功后的回调函数
                          Toast({
                            message: "支付成功!",
                            overlay: true,
                            loadingType: "spinner",
                            onClose: () => {
                              that.$router.go(-1);
                            }
                          });
                        }
                      });
                    });
                  });
                });
              }
            });
          });
      } else {
        /**未选择收货地址 */
        Toast({
          message: "前往选择收货地址",
          overlay: true,
          loadingType: "spinner",
          onClose: () => {
            let params = {
              product_id: this.id,
              user_id: this.userId,
              num: num
            };
            this.$router.push({
              name: "addressList",
              query: { params: params }
            });
          }
        });
        return;
      }
    }
  },
  mounted() {
    let id = this.$route.query.id;
    this.id = id;
    productsView({ id: id }).then(res => {
      // eslint-disable-next-line
      console.log(res);
      this.details = res;
    });

    //   请求收货地址列表
    addressIndex({
      user_id: this.userId
    }).then(res => {
      // eslint-disable-next-line
      console.log(res);
      res.map(e => {
        if (e.is_default == 1) {
          this.defaultAddress = e;
          return;
        }
      });
    });

    getWxConfig().then(res => {
      wx.config({
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: res.appId, // 必填，公众号的唯一标识
        timestamp: res.timeStamp, // 必填，生成签名的时间戳
        nonceStr: res.nonceStr, // 必填，生成签名的随机串
        signature: res.signature, // 必填，签名
        jsApiList: ["chooseWXPay"] // 必填，需要使用的JS接口列表
      });
      wx.ready(function() {
        wx.checkJsApi({
          jsApiList: ["chooseWXPay"],
          success: function() {},
          fail: function() {}
        });
      });
    });
  }
};
</script>
<style lang="less" scoped>
.addressBox {
  padding: 15px;
}
.wrapper {
  background: white;
  bottom: 0;
  position: absolute;
  left: 0;
  right: 0;
  z-index: 333;
}
.pro-wrap {
  display: flex;
  padding: 20px 15px;
  line-height: 24px;
  img {
    width: 90px;
    height: 90px;
  }
  div {
    flex: 1;
    margin-left: 10px;
    p {
      color: #666666;
      font-size: 12px;
      display: flex;
      align-items: center;
    }
  }
}
.detail-wrap {
  margin-bottom: 50px;
}
.bg-white {
  background: white;
}
.p10 {
  padding: 10px;
}
.detail-cont {
  img {
    width: 100%;
  }
}
.price {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  b {
    color: #020202;
    font-size: 16px;
  }
  em {
    color: #666666;
    font-size: 12px;
  }
}
.btn-fix {
  bottom: 0;
}
.tips {
  position: fixed;
  top: 6%;
  right: 0;
  z-index: 3;
  background: rgba(black, 0.3);
  color: white;
  height: 23px;
  line-height: 23px;
  padding: 0 20px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  font-size: 12px;
}
</style>